//
//  MedicalOfficeViewController.m
//  安好
//
//  Created by lianchuang on 14-11-13.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MedicalOfficeViewController.h"
#import "MyChineseBookAddress.h"
#import "DestDetailViewController.h"
@interface MedicalOfficeViewController ()
{
    FKSearchBar * illSeachBar;

}
@end

@implementation MedicalOfficeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.deskArray = [[NSMutableArray alloc]init];
    self.deskAllArray = [[NSMutableArray alloc]init];
    self.deskNameArray = [[NSMutableArray alloc]init];
    nameDic = [[NSMutableDictionary alloc] init];
    self.deskSearchArray = [[NSMutableArray alloc]init];
    [self makeNavBar];
    [self loadData];
    [self markIllnessSearchBar];
    [self makeIllnessTableView];
}
#pragma - mark searchBar
- (void)markIllnessSearchBar
{
    illSeachBar = [[FKSearchBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    illSeachBar.searchTextField.placeholder = @"科室";
    illSeachBar.fkSearchRequestDelegate = self;
    [self.view addSubview:illSeachBar];
}
#pragma - mark tableView
/**
 *  加载tableView
 */
- (void)makeIllnessTableView
{
    self.deskTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,44, kScreenWidth, kScreenHeight - iOS7TopMargin - 44.1) style:UITableViewStylePlain];
    self.deskTableView.delegate = self;
    self.deskTableView.dataSource = self;
    self.deskTableView.showsHorizontalScrollIndicator = NO;
    self.deskTableView.showsVerticalScrollIndicator = NO;
    [self.deskTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉系统的分割线
    self.deskTableView.sectionIndexBackgroundColor =[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.deskTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.deskTableView.sectionIndexColor= [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
  [self.view addSubview:self.deskTableView];
}
-(void)makeNavBar
{
    self.navigationItem.title = @"科室";
    // “返回”
    UIBarButtonItem *backBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBackDown)];
    backBtnItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnItem;
    // “筛选”
}
//返回 百科页面
-(void)leftBackDown
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 数据加载
-(void)loadData
{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
   
    [dict setObject:@"1" forKeyedSubscript:@"returnType"];
    [dict setObject:@"0" forKeyedSubscript:@"parentdeptid"];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@wiki/department/",kBaseURL] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            if ([self.deskArray count] != 0){
                [self.deskArray removeAllObjects];
            }
            if ([self.deskAllArray count] != 0) {
                [self.deskAllArray removeAllObjects];
            }
            if (jsonDictArr!=nil) {
                for (NSDictionary * dic in jsonDictArr){
                    [self.deskArray addObject:dic];
                    [self.deskNameArray addObject:[dic objectForKey:@"departmentname"]];
                    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:[dic objectForKey:@"departmentid"]forKey:[dic objectForKey:@"departmentname"]];
                }
                [self.deskTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];//去掉系统的分割线

                
                for (int i=0; i<self.deskNameArray.count; i++) {
                    
                    if ([[self.deskNameArray objectAtIndex:i] canBeConvertedToEncoding:NSASCIIStringEncoding]) {
                        
                        [self.deskAllArray addObject:[NSString stringWithFormat:@"%c", [[self.deskNameArray objectAtIndex:i] characterAtIndex:0]]];
                        
                    }else{
                        char firstChar = pinyinFirstLetter([[self.deskNameArray objectAtIndex:i] characterAtIndex:0]);
                        NSString *youName = [NSString stringWithFormat:@"%c",firstChar];
                        //不添加重复元素
                        if (![self.deskAllArray containsObject:[youName uppercaseString]]) {
                            [self.deskAllArray addObject:[youName uppercaseString]];
                        }
                        
                    }

                }
                [self.deskAllArray sortUsingSelector:@selector(compare:)];
                
                //每个section对应的行数列表
                for(NSString * sectionString  in self.deskAllArray)
                {
                    NSMutableArray *rowSource = [[NSMutableArray alloc] init];
                    
                    for (NSString *charString in self.deskNameArray) {
                        
                        char firstchar;
                        
                        if ([charString canBeConvertedToEncoding:NSASCIIStringEncoding]){
                            
                            firstchar = [charString characterAtIndex:0];
                        }else{
                            
                            firstchar = pinyinFirstLetter([charString characterAtIndex:0]);
                        }
                        NSString *youName = [NSString stringWithFormat:@"%c",firstchar];
                        if ([sectionString isEqualToString:[youName uppercaseString]]) {
                            [rowSource addObject:charString];
                        }
                        
                    }
                    
                    [nameDic setValue:rowSource forKey:sectionString];

                }

                
                [self.deskTableView reloadData];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];
    
}
#pragma mark 2中cell的加载
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.isSearch == YES) {
        return 1;
    }else{
    return [self.deskAllArray count];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isSearch == YES) {
        return [self.deskSearchArray count];
    }else{
    NSArray *dicCount = [nameDic objectForKey:[self.deskAllArray objectAtIndex:section]];
    NSSet *set = [NSSet setWithArray:dicCount];

    return [[set allObjects] count];
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isSearch == YES) {
        static NSString * identifier = @"myCell";
        //  检测、查询是否有闲置的单元格
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil){
            cell =  [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        NSDictionary * sectionDic = [self.deskSearchArray objectAtIndex:indexPath.row];
        
        cell.textLabel.text = [sectionDic objectForKey:@"departmentname"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = [UIColor colorWithRed:31.0/255 green:33.0/255 blue:36.0/255 alpha:1];
        return cell;
    }else{
    static NSString * identifier = @"myCell";
    //  检测、查询是否有闲置的单元格
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell =  [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSString * sectionString = [self.deskAllArray objectAtIndex:indexPath.section];
    
    NSArray *allShowName = [nameDic objectForKey:sectionString];
    if (allShowName.count>0) {
        cell.textLabel.text = [allShowName objectAtIndex:indexPath.row];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:TITLE_TEXTLABEL_FOUNT_SIZE];
    cell.textLabel.textColor = [UIColor colorWithRed:31.0/255 green:33.0/255 blue:36.0/255 alpha:1];
    return cell;
    }
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.isSearch == YES) {
        return nil;
    }else{
    return [self.deskAllArray objectAtIndex:section];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 31)];
        view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
        UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(15, 6, 20, 20)];
        imageview.backgroundColor = [UIColor lightGrayColor];
//        [view addSubview:imageview];
    
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(15, 6, 20, 20)];
        label.text=[self.deskAllArray objectAtIndex:section];
        label.textAlignment=NSTextAlignmentCenter;
        label.backgroundColor=[UIColor clearColor];
        label.textColor=[UIColor blackColor];
        [view addSubview:label];
        return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 31;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(kScreenWidth == 414){
        return 56;
    }else{
    return 40;
    }
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.deskAllArray;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if (self.isSearch == YES) {
        return 0;
    }else{
        NSInteger count = 0;
        
        for(NSString *character in self.deskAllArray)
        {
            if([character isEqualToString:title]) return count;
            count ++;
        }
        
        return 0;
    }
   
}
#pragma - mark FKSearchDelegate
/**
 *  FKSearch的delegate
 */
- (void)VoiceConversion
{
    [illSeachBar.searchTextField resignFirstResponder];
    [self starVoice];
}
- (void)voice:(NSString *)voice
{
    illSeachBar.searchTextField.text = voice;
    self.searchDesk = voice;
    self.isSearch = YES;
    if ([self.deskSearchArray count] != 0) {
        [self.deskSearchArray removeAllObjects];
    }
    for (NSDictionary * dic in self.deskArray) {
        NSString *name = [dic objectForKey:@"departmentname"];
        NSRange range = [name rangeOfString:voice];
        if (range.location != NSNotFound) {
            [self.deskSearchArray addObject:dic];
        }
    }
    if ([self.deskSearchArray count] == 0){
        self.isSearch = NO;
        [self loadData];
    }else{
        [self.deskTableView reloadData];
    }
}
- (void)SearchString
{
    [illSeachBar.searchTextField resignFirstResponder];
    self.searchDesk = illSeachBar.searchTextField.text;
    self.isSearch = YES;
    if ([self.deskSearchArray count] != 0) {
        [self.deskSearchArray removeAllObjects];
    }
    for (NSDictionary * dic in self.deskArray) {
        NSString *name = [dic objectForKey:@"departmentname"];
        NSRange range = [name rangeOfString:self.searchDesk];
        if (range.location != NSNotFound) {
            [self.deskSearchArray addObject:dic];
        }
    }
    if ([self.deskSearchArray count] == 0){
        self.isSearch = NO;
        [self loadData];
    }else{
        [self.deskTableView reloadData];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isSearch == YES) {
        DestDetailViewController * deskDetailViewController = [[DestDetailViewController alloc]init];
        NSDictionary * sectionDic = [self.deskSearchArray objectAtIndex:indexPath.row];
        NSString * deskname = [sectionDic objectForKey:@"departmentname"];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString * deskid = [userDefaults objectForKey:deskname];
        deskDetailViewController.hosname = deskname;
        deskDetailViewController.hoskid = deskid;
        [self.navigationController pushViewController:deskDetailViewController animated:YES];
    }else{
    DestDetailViewController * deskDetailViewController = [[DestDetailViewController alloc]init];
    NSString * sectionString = [self.deskAllArray objectAtIndex:indexPath.section];
    
    NSArray *allShowName = [nameDic objectForKey:sectionString];
    if (allShowName.count>0) {
        deskDetailViewController.hosname = [allShowName objectAtIndex:indexPath.row];
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString * deskid = [userDefaults objectForKey:[allShowName objectAtIndex:indexPath.row]];
    deskDetailViewController.hoskid = deskid;
    [self.navigationController pushViewController:deskDetailViewController animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
